package com.hzdl.car.controller;

import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.Menu;
import com.hzdl.car.service.LogService;
import com.hzdl.car.util.AJAXResult;
import com.hzdl.car.util.TreeNode;
import com.hzdl.car.bean.User;
import com.hzdl.car.service.MenuService;
import com.hzdl.car.service.UserService;
import com.hzdl.car.util.ConnUtil1;
import com.hzdl.car.vo.LogVo;
import com.hzdl.car.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService us;
    @Autowired
    private MenuService ms;
    @Autowired
    private LogService ls;
     @RequestMapping("/loginInit")
    public String loginInit(){
         return "system/login";
     }
     @RequestMapping("/login")
    public String login(Model model, UserVo userVo, HttpSession session,HttpServletRequest req){
         User user1 = us.findUser(userVo);
         if(user1==null){
             model.addAttribute("msg","账号与用户名不匹配");
             return "redirect:/user/loginInit";
         }else{
             LogVo logVo = new LogVo();
             logVo.setLoginname(user1.getLoginname()+"-"+user1.getRealname());
             //获取ip地址
             String ip=req.getRemoteAddr();
             logVo.setLoginip(ip);
             ls.insertLogInfo(logVo);
             session.setAttribute("user",user1);
             return "system/index";
         }
     }
     @RequestMapping("/generateYzm")
    public void generateYzm(HttpServletRequest req, HttpServletResponse resp) throws IOException {
         String autoYzm = ConnUtil1.generateVerifyCode(4);
         req.getSession().setAttribute("AUTOYZM",autoYzm);
         //输出指定验证码图片流
         ConnUtil1.outputImage(100,30,resp.getOutputStream(),autoYzm);
     }
     @RequestMapping("/chkYzm")
    public void chkYzm(HttpServletRequest req,HttpServletResponse resp,String code1) throws IOException {
         String yzm=(String)req.getSession().getAttribute("AUTOYZM");
         int  i =0;
         if(!code1.equalsIgnoreCase(yzm)){
             i=1;
         }
         PrintWriter out = resp.getWriter();
         out.print(i);
         out.close();
     }
     @RequestMapping("/deskManagerInit")
    public String deskManagerInit(){
         return "system/deskManager";
     }

     @RequestMapping("/leftMenu")
     @ResponseBody
    public Map<String,Object> leftMenu(HttpSession session){
         Map<String,Object> map = new HashMap<>();
         Object object = session.getAttribute("user");
         if(object!=null){
             User user = (User) object;
             List<Menu> all=null;
             if(user.getType()!=null&&user.getType()==1){
                 all = ms.findAll();
                 List<TreeNode> treeNodes = new ArrayList<>();
                 // 查询出来的菜单集合 转换为 需要的类型TreeNode（页面需要的类型）
                 for(Menu menu:all){
                     TreeNode treeNode = new TreeNode(menu.getId(),menu.getPid(),
                             menu.getName(),menu.getIcon(),
                             menu.getHref(),menu.getOpen()==1?true:false);
                     treeNodes.add(treeNode);
                 }
                 List<TreeNode> treeNodeList = new ArrayList<>();
                 // 区分一级菜单还是二级菜单
                 for(TreeNode treeNode:treeNodes){
                     if(treeNode.getPid()!=null&&treeNode.getPid()==1){
                         treeNodeList.add(treeNode);
                         continue;
                     }
                     for(TreeNode treeNode1:treeNodeList){
                         if(treeNode.getPid() != null && treeNode.getPid() == treeNode1.getId() ){
                             treeNode1.getChildren().add(treeNode);
                         }
                     }
                 }
                 map.put("contentManagement",treeNodeList);
             }else{
                 all=us.findMenuByUserId(user.getUserid());
             }
             List<TreeNode> treeNodes = new ArrayList<>();
             // 查询出来的菜单集合 转换为 需要的类型TreeNode（页面需要的类型）
             for(Menu menu:all){
                 TreeNode treeNode = new TreeNode(menu.getId(),menu.getPid(),
                         menu.getName(),menu.getIcon(),
                         menu.getHref(),menu.getOpen()==1?true:false);
                 treeNodes.add(treeNode);
             }
             List<TreeNode> treeNodeList = new ArrayList<>();
             // 区分一级菜单还是二级菜单
             for(TreeNode treeNode:treeNodes){
                 if(treeNode.getPid()!=null&&treeNode.getPid()==1){
                     treeNodeList.add(treeNode);
                     continue;
                 }
                 for(TreeNode treeNode1:treeNodeList){
                     if(treeNode.getPid() != null && treeNode.getPid() == treeNode1.getId() ){
                         treeNode1.getChildren().add(treeNode);
                     }
                 }
             }
             map.put("contentManagement",treeNodeList);
       }
       return map;
     }
     @RequestMapping("/userInit")
    public String userInit(){
         return "/system/user";
     }
     @RequestMapping("/userShow")
     @ResponseBody
     public AJAXResult userShow(UserVo userVo){
         if(userVo.getPage()==null){
             userVo.setPage(1);
         }
         if(userVo.getLimit()==null){
             userVo.setLimit(5);
         }
         PageInfo pageInfo=us.findByWhere(userVo);
         return new AJAXResult(0,"",pageInfo.getList(),pageInfo.getTotal());

     }
     @RequestMapping("/addUser")
     @ResponseBody
     public AJAXResult addUser(UserVo userVo){
         if(userVo.getUserid()==null){
             int row=us.addRoleUser(userVo);
             if(row==0){
                 return AJAXResult.ADD_ERROR;
             }
             return AJAXResult.ADD_SUCCESS;
         }else{
             int row=us.updateUser(userVo);
             if(row==0){
                 return AJAXResult.UPDATE_ERROR;
             }
             return AJAXResult.UPDATE_SUCCESS;
         }
     }
     @RequestMapping("/userDelete")
     @ResponseBody
     public AJAXResult userDelete(UserVo userVo){
         int row=us.deleteUser(userVo);
         if(row==0){
             return AJAXResult.DELETE_ERROR;
         }
         return AJAXResult.DELETE_SUCCESS;
     }

     @RequestMapping("/deleteAllUser")
     @ResponseBody
     public AJAXResult deleteAllUser(String ids){
         String[] id = ids.split(",");
         int row=0;
         for(int i = 0;i<id.length;i++){
             UserVo uv= new UserVo();
             uv.setUserid(Integer.valueOf(id[i]));
             row+=us.deleteUser(uv);
         }
         if(row==0){
             return AJAXResult.DELETE_ERROR;
         }
         return AJAXResult.DELETE_SUCCESS;

     }
     @RequestMapping("/resetPwd")
     @ResponseBody
     public AJAXResult resetPwd(UserVo userVo){
       int row=us.resetPwd(userVo);
       if(row==0){
           return AJAXResult.RESET_ERROR;
       }
       return AJAXResult.RESET_SUCCESS;

     }
    @RequestMapping("/findRoleByUser")
    @ResponseBody
    public AJAXResult findRoleByUser(UserVo userVo){
        return new AJAXResult(0,"",us.findRole(userVo.getUserid()));
    }

    /**
     * 用户管理-分配角色功能
     * @param userVo
     * @return
     */
    @RequestMapping("/saveRoleUser")
    @ResponseBody
    public AJAXResult saveRoleUser(UserVo userVo){

        int row = us.updateRoleUser(userVo);
        if(row == 0){
            return AJAXResult.DISPATCH_ERROR;
        }

        return AJAXResult.DISPATCH_SUCCESS;
    }




}
